package dice.sinanya.listener;

import com.forte.qqrobot.anno.timetask.CronTask;
import com.forte.qqrobot.beans.messages.result.inner.Group;
import com.forte.qqrobot.exception.TimeTaskException;
import com.forte.qqrobot.sender.MsgSender;
import com.forte.qqrobot.timetask.TimeJob;
import com.forte.qqrobot.timetask.TimeTaskContext;
import com.forte.qqrobot.utils.CQCodeUtil;
import dice.sinanya.db.heap.InsertHeap;
import dice.sinanya.db.lastMessages.SelectLastMessages;
import dice.sinanya.dice.MakeNickToSender;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.quartz.JobExecutionContext;

import java.util.ArrayList;

import static dice.sinanya.db.system.InsertBot.deleteBot;
import static dice.sinanya.db.system.SelectBot.*;
import static dice.sinanya.system.MessagesBanList.groupWhiteList;
import static dice.sinanya.system.MessagesSystem.isRunning;
import static dice.sinanya.system.MessagesSystem.loginInfo;
import static dice.sinanya.tools.checkdata.CheckIsNumbers.isNumeric;
import static dice.sinanya.tools.checkdata.imal.GetZk.getInGroupZNodeActive;
import static dice.sinanya.tools.checkdata.imal.LeaveGroup.leaveGroup;
import static dice.sinanya.tools.getinfo.GetMessagesProperties.entityBanProperties;
import static dice.sinanya.tools.getinfo.GetNickName.getGroupName;
import static dice.sinanya.tools.makedata.RandomInt.random;

/**
 * @author SitaNya
 * 日期: 2019-06-15
 * 电子邮箱: sitanya@qq.com
 * 维护群(QQ): 162279609
 * 有任何问题欢迎咨询
 * 类说明: 定时任务类，会根据设定的时间每隔多久自动执行一次
 * <p>
 * 这里的“0 * * * * ? *”表示每分钟执行一次，具体怎么写请去查crontab的使用
 * 前5位应该是:分 时 日 月 周
 */

@CronTask("0 0/5 * * * ? *")
//@CronTask("0 * * * * ? *")
public class TestRunningTime implements TimeJob, MakeNickToSender {
    private static final Logger log = LogManager.getLogger(TestRunningTime.class.getName());
    private MsgSender msgSender;
    private boolean inManager = false;
    SelectLastMessages selectLastMessages;

    public TestRunningTime() {
        selectLastMessages = new SelectLastMessages();
    }

    @Override
    public void execute(MsgSender msgSender, CQCodeUtil cqCodeUtil) {
        if (!isRunning) {
            return;
        }
        flushBotList(msgSender);
        this.msgSender = msgSender;
        if (checkHasGroup(Long.parseLong(entityBanProperties.getManagerGroup()))) {
            this.inManager = true;
        }
        autoClean();
        try {
            Thread.sleep(random(2000, 12000));
        } catch (InterruptedException e) {
            log.error(e.getMessage(), e);
        }
        autoCleanNotPlay();
        try {
            if (loginInfo.getLoginId() != -10006) {
                new InsertHeap().updateHeap();
            } else {
                log.error("当前识别QQ号错误");
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            log.error("获取群列表失败，停止心跳");
        }
    }

    @Override
    public void execute(JobExecutionContext context) {
        try {
            CQCodeUtil cqCodeUtil = TimeTaskContext.getCQCodeUtil(context);
            MsgSender msgSender = TimeTaskContext.getMsgSender(context);
            execute(msgSender, cqCodeUtil);
        } catch (Exception e) {
            throw new TimeTaskException(e);
        }
    }


    private void autoClean() {
        ArrayList<String> offBotList = selectOffBotList();
        ArrayList<Long> botList = selectBotList();

        Group[] groupList = msgSender.GETTER.getGroupList().getList();
        ArrayList<Long> groupListCode = new ArrayList<>();
        for (Group group : groupList) {
            groupListCode.add(Long.valueOf(group.getCode()));
        }

        for (long botGroupIdString : botList) {
            if (!groupListCode.contains(botGroupIdString)) {
                deleteBot(botGroupIdString);
//                sendToManager("删除已不存在群： " + botGroupIdString);
            }
        }

        for (String offBotGroupIdString : offBotList) {
            long offBotGroupId = Long.parseLong(offBotGroupIdString);
            if (groupWhiteList.contains(offBotGroupId) || entityBanProperties.getManagerGroup().equals(offBotGroupIdString)) {
                continue;
            }
            long tmp = msgSender.GETTER.getGroupMemberInfo(offBotGroupIdString, String.valueOf(loginInfo.getLoginId())).getLastTime();
            if (selectLastMessages.selectLastMessages(entityBanProperties.getClearGroupByOff()).contains(offBotGroupId)) {
                try {
                    sendToManager("已清理" + entityBanProperties.getClearGroupByOff() + "日未使用，且已关闭本骰的群: " + makeGroupNickToSender(getGroupName(msgSender, offBotGroupIdString)) + offBotGroupId);
                    msgSender.SENDER.sendGroupMsg(offBotGroupIdString, String.format(entityBanProperties.getClearGroupByOffInfo(), makeGroupNickToSender(getGroupName(msgSender, offBotGroupIdString)) + "(" + offBotGroupId + ")", entityBanProperties.getClearGroupByOff()));
                    msgSender.SENDER.sendDiscussMsg(String.valueOf(offBotGroupId), "已在讨论组: " + makeGroupNickToSender(getGroupName(msgSender, offBotGroupIdString)) + offBotGroupId + "中超过" + entityBanProperties.getClearGroupByOff() + "日未响应且处于关闭状态，即将退群。\n此次退群不会记录黑名单，如遇到问题请至群162279609进行反馈或使用退群命令缓解问题");
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                } finally {
                    leaveGroup(msgSender, offBotGroupId);
                    deleteBot(offBotGroupId);
                }
                return;
            }
        }
    }

    private void autoCleanNotPlay() {
        Group[] groupLists = msgSender.GETTER.getGroupList().getList();
        for (Group group : groupLists) {
            long notPlayBotGroupId = Long.parseLong(group.getCode());
            if (groupWhiteList.contains(notPlayBotGroupId) || entityBanProperties.getManagerGroup().equals(group.getCode())) {
                continue;
            }

            if (selectLastMessages.selectLastMessages(entityBanProperties.getClearGroup()).contains(notPlayBotGroupId) && getInGroupZNodeActive(String.valueOf(notPlayBotGroupId), null)) {
                try {
                    sendToManager("已清理" + entityBanProperties.getClearGroup() + "日未使用的群: " + makeGroupNickToSender(getGroupName(msgSender, String.valueOf(notPlayBotGroupId))) + notPlayBotGroupId);
                    msgSender.SENDER.sendGroupMsg(String.valueOf(notPlayBotGroupId), String.format(entityBanProperties.getClearGroupInfo(), makeGroupNickToSender(getGroupName(msgSender, String.valueOf(notPlayBotGroupId))) + "(" + notPlayBotGroupId + ")", entityBanProperties.getClearGroup()));
                    msgSender.SENDER.sendDiscussMsg(String.valueOf(notPlayBotGroupId), String.format(entityBanProperties.getClearGroupInfo(), makeGroupNickToSender(getGroupName(msgSender, String.valueOf(notPlayBotGroupId))) + "(" + notPlayBotGroupId + ")", entityBanProperties.getClearGroup()));
                } catch (Exception exception) {
                    log.error(exception.getMessage(), exception);
                } finally {
                    leaveGroup(msgSender, notPlayBotGroupId);
                    deleteBot(notPlayBotGroupId);
                }
                return;
            }
        }
    }

    private boolean checkHasGroup(long groupId) {
        Group[] groupList = msgSender.GETTER.getGroupList().getList();
        for (Group group : groupList) {
            if (groupId == Long.parseLong(group.getCode())) {
                return true;
            }
        }
        return false;
    }

    private void sendToManager(String info) {
        if (inManager) {
            msgSender.SENDER.sendGroupMsg(entityBanProperties.getManagerGroup(), info);
        } else {
            for (String master : entityBanProperties.getMaster()) {
                if (isNumeric(master)) {
                    msgSender.SENDER.sendPrivateMsg(master, info);
                }
            }
        }
    }
}